<template>
  <div>
    <BasicTable @register="registerTable" @edit-end="handleUpdate">
      <template #tableTitle>
        <AButton type="primary" @click="openModal"> {{ t('common.addText') }} </AButton>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'fa-solid:trash-alt',
              color: 'error',
              tooltip: t('common.delText'),
              popConfirm: {
                title: t('tips.deleteOrNot'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @create="handleCreate" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import FormModal from './FormModal.vue';
  import { getTableProps } from './tableData';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isArray } from '/@/utils/is';
  import { patientApi } from '/@/api/console/patient';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal/src/hooks/useModal';
  export default defineComponent({
    name: 'Patient',
    components: { BasicTable, TableAction, FormModal },
    setup() {
      const { t } = useI18n();
      const { createMessage } = useMessage();
      const checkedKeys = ref<Array<string | number>>([]);
      const [registerTable, { setTableData, getDataSource }] = useTable(getTableProps());
      const [registerModal, { openModal }] = useModal();

      const handleCreate = async (record: Recordable) => {
        setTableData([record, ...getDataSource()]);
        createMessage.success(t('tips.createSuccess'));
      };

      const handleUpdate = async ({ record, key, value }) => {
        const params = {};
        params[isArray(key) ? key[0] : key] = value;
        await patientApi.update(record.id, params);
      };

      const handleDelete = async (record: Recordable) => {
        await patientApi.delete(record.id);
        const data = getDataSource().filter((item) => item.id !== record.id);
        setTableData(data);
        createMessage.success(t('tips.deleteSuccess'));
      };

      return {
        t,
        registerTable,
        registerModal,
        handleCreate,
        handleUpdate,
        handleDelete,
        openModal,
        checkedKeys,
      };
    },
  });
</script>
